package cn.uestc.labhms.modules.hms.controller;

import cn.uestc.labhms.common.annotation.SysLog;
import cn.uestc.labhms.common.utils.R;
import cn.uestc.labhms.modules.hms.entity.Vo.*;
import cn.uestc.labhms.modules.hms.service.TableService;
import cn.uestc.labhms.modules.hms.util.HMSPageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Mu.tz
 */
@RestController
public class TableController {
    @Autowired
    private TableService tableService;

    @GetMapping("/get/table/names")
    public R getTableNames() {
        TableNamesVo tableNames = tableService.getTableNames();
        return R.ok().put("data", tableNames);
    }
    @GetMapping("/get/hms_Chi_Eng/fields")
    public R getTableFields(String tableName) {
        List<String> tableFields = tableService.getTableFields(tableName);
        return R.ok().put("data", tableFields);
    }
    @GetMapping("/get/table/data")
    @SysLog("单表查询")
    public R getConditionFind(@Validated ConditionsFindVo conditionsFindVo) {
        HMSPageUtils conditionsFind = tableService.getConditionsFind(conditionsFindVo);
        return R.ok().put("data", conditionsFind);
    }
    @PostMapping("/put/table/row")
    @SysLog("新增一行数据")
    public R addRow(@Validated @RequestBody SaveOrUpdateRowVo saveOrUpdateRowVo) {
        tableService.insertRowByMap(saveOrUpdateRowVo.getTableNameC(), saveOrUpdateRowVo.getRow());
        return R.ok();
    }
    @PostMapping("/post/table/row")
    @SysLog("更新一行数据")
    public R updateRow(@Validated @RequestBody SaveOrUpdateRowVo saveOrUpdateRowVo) {
        tableService.updateRowByMap(saveOrUpdateRowVo.getTableNameC(), saveOrUpdateRowVo.getRow());
        return R.ok();
    }
    @PostMapping("/delete/table/row")
    @SysLog("删除一行数据")
    public R deleteRow(@Validated @RequestBody DeleteRowVo deleteRowVo) {
        int effcntRow = tableService.deleteRowById(deleteRowVo.getTableNameC(), deleteRowVo.getId());
        if (effcntRow == 0) {
            return R.ok("删除成功，但未删除任何行，可能是数据库中无该主键值");
        }
        return R.ok();
    }
    @GetMapping("/get/table/id/name")
    public R getIdName(@RequestParam("tableName") String tableNameC) {
        String idName = tableService.getIdName(tableNameC);
        Map<String, String> map = new HashMap<>(1);
        map.put("IdName4Head", idName);
        return R.ok().put("data", map);
    }
    @PostMapping("/update/add/field")
    @SysLog("增加表中字段")
    @RequiresPermissions("hms:table_structure:update")
    public R addXlsxField(@Validated @RequestBody AddFieldVo addFieldVo) {
        tableService.addXlsxField(addFieldVo);
        return R.ok();
    }
}
